<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use App\Models\Order;
use App\Models\DayOrderReport;
use App\Models\QrcodeToken;
use App\Models\Shops;
use Carbon\Carbon;

class Kernel extends ConsoleKernel {

    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
            //
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule) {
        $schedule->call(function () {
            //每天凌晨重新统计之前所有的数据报表
            \DB::table('day_order_reports')->truncate();
            $earliestOrder = Order::min('created_at'); //最早的订单
            $dt = Carbon::parse($earliestOrder);
            $startDt = $dt->hour(0)->minute(0)->second(0)->toDateTimeString();
            $endDt = $dt->hour(23)->minute(59)->second(59)->toDateTimeString();
            while (!$dt->isToday()) {
                DayOrderReport::create([
                    'total' => Order::where('created_at', '>=', $startDt)->where('created_at', '<=', $endDt)->sum('total'),
                    'pay_total' => Order::where('created_at', '>=', $startDt)->where('created_at', '<=', $endDt)->where('state', 1)->sum('total'),
                    'amount' => Order::where('created_at', '>=', $startDt)->where('created_at', '<=', $endDt)->sum('amount'),
                    'order_date' => $dt->toDateString(),
                ]);
                $startDt = $dt->addDay()->hour(0)->minute(0)->second(0)->toDateTimeString();
                $endDt = $dt->hour(23)->minute(59)->second(59)->toDateTimeString();
            }
        })->daily();
    }

    /**
     * Register the Closure based commands for the application.
     *
     * @return void
     */
    protected function commands() {
        require base_path('routes/console.php');
    }

}
